package com.bjpowernode.seckillservice.task;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Goods;
import com.bjpowernode.seckillservice.service.GoodsService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 开启定时任务完成商品缓存预热
 */
@EnableScheduling
@Component
public class GoodsTask {

    @Resource
    private GoodsService goodsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 缓存预热
     */
    @Scheduled(cron = "0/3 * * * * *")
    public void initGoodsCache(){
        //从mysql中查询所有参与秒杀的商品
        List<Goods> list = goodsService.list();

        //将mysql商品数据保存到redis中
        list.forEach(goods -> {
            //放入商品对象
            redisTemplate.opsForValue().set(Constants.REDIS_GOODS + goods.getId(), goods);

            //若redis中不存在库存，则放入商品库存
            //setIfAbsent 若redis中不存在该key则放入，否则就不放入
            stringRedisTemplate.opsForValue().setIfAbsent(Constants.REDIS_STORE + goods.getId(), goods.getStore().toString());
        });
    }
}
